package com.idroc.message.impl;

import java.util.concurrent.atomic.AtomicLong;

import org.apache.mina.common.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.idroc.message.Message;
import com.idroc.message.MessageHandler;
import com.idroc.message.MessageService;

public class HeartBeatMessageHandler implements MessageHandler {
	
	private static final Logger log = LoggerFactory.getLogger(HeartBeatMessageHandler.class);
	
	static AtomicLong nextHeatBeat = new AtomicLong(0);
	static long detectedHeatBeat = 0;
	
	private MessageService service = null;
	
	int runStyle = 0; // 0: server, 1: client

	public void onAttached(MessageService service) {
		
		this.service = service;
		log.info("service:{}", service);
	}

	public void onMsgCast(IoSession s, Message message) {

		HeartBeatMessage msg = (HeartBeatMessage)message;
		log.debug("message:{}", msg);
	}

	public void onMsgReceived(IoSession s, Message message) {

		HeartBeatMessage msg = (HeartBeatMessage)message;
		log.debug("HeartBeatMessage:{}", msg);
		if (runStyle == 0) {
			runServerSide(msg);
		} else {
			runClientSide(msg);
		}
	}

	public void onMsgSent(IoSession s, Message message) {

		HeartBeatMessage msg = (HeartBeatMessage)message;
		log.debug("lastImpulseHeatBeat:" + msg.getHeartBeat());
	}

	public void onReleased(MessageService service) {

		this.service = null;
		log.info("service:{}", service);
	}
	
	void runServerSide(HeartBeatMessage msg) {
		
		detectedHeatBeat += msg.getHeartBeat();
		HeartBeatMessage rtv = new HeartBeatMessage();
		rtv.setHeartBeat(1l);

		System.out.println("ServerSide->detectedHeatBeat:" + detectedHeatBeat);
		// service.sendMessage(rtv);
	}
	
	void runClientSide(HeartBeatMessage msg) {
		
		detectedHeatBeat += msg.getHeartBeat();
		System.out.println("ClientSide->detectedHeatBeat:" + detectedHeatBeat);
		if (detectedHeatBeat < 10000000) {
			HeartBeatMessage rtv = new HeartBeatMessage();
			rtv.setHeartBeat(1l);
		//	service.sendMessage(rtv);
		} else {
			System.out.println("done.");
		}
	}

}
